package cn.lg.soar.system.auth.service;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.current.CurrentProxy;
import cn.lg.soar.system.auth.entity.UserOrg;
import cn.lg.soar.system.auth.mapper.UserOrgMapper;
import cn.lg.soar.system.auth.model.UserOrgItemVO;
import cn.lg.soar.system.config.AuthCacheKey;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2022/4/10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class UserOrgService extends ServiceImpl<UserOrgMapper, UserOrg> implements CurrentProxy<UserOrgService> {

    /**
     * 根据用户id获取机构
     * @param userId
     * @return
     */
    @Cacheable(value = AuthCacheKey.ORG_ID_BY_USER, key = "#userId", cacheManager = "remote")
    public List<UserOrgItemVO> getOrgs(Long userId) {
        List<UserOrg> list = list(
                Wrappers.<UserOrg>lambdaQuery()
                        .select(UserOrg::getOrgId, UserOrg::getPostId, UserOrg::getMain)
                        .eq(UserOrg::getUserId, userId)
                        .orderByDesc(UserOrg::getMain, UserOrg::getId)
        );
        return list.stream().map(x -> {
            UserOrgItemVO vo = new UserOrgItemVO();
            vo.setOrgId(x.getOrgId());
            vo.setPostId(x.getPostId());
            vo.setMain(x.getMain());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 设置用户机构
     * @param userId
     * @param orgIds
     */
    @CacheEvict(value = {AuthCacheKey.ORG_ID_BY_USER, AuthCacheKey.ROLE_ID_BY_USER_ALL, AuthCacheKey.ORG_ID_BY_USER_ALL}, key = "#userId")
    @Transactional(rollbackFor = RuntimeException.class)
    public void setUserOrg(Long userId, Collection<UserOrgItemVO> orgs) {
        // 清空旧值
        clearByUser(userId);
        // 批量保存新值
        if (CollectionUtils.isEmpty(orgs)) {
            return;
        }

        Long mainId = null;
        for (UserOrgItemVO org : orgs) {
            if (Boolean.TRUE.equals(org.getMain())) {
                AssertUtil.isTrue(mainId == null, "主职部门只能有一个");
                mainId = org.getOrgId();
            }
        }
        List<UserOrg> collect = orgs.stream()
                .distinct()
                .map(x -> {
                    UserOrg data = new UserOrg();
                    data.setUserId(userId);
                    data.setMain(x.getMain());
                    data.setOrgId(x.getOrgId());
                    data.setPostId(x.getPostId());
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存用户机构失败");
    }

    @CacheEvict(value = {AuthCacheKey.ORG_ID_BY_USER, AuthCacheKey.ROLE_ID_BY_USER_ALL, AuthCacheKey.ORG_ID_BY_USER_ALL}, key = "#userId")
    public void clearByUser(Long userId) {
        this.remove(Wrappers.<UserOrg>lambdaQuery().eq(UserOrg::getUserId, userId));
    }

    public void clearByOrg(Long orgId) {
        this.remove(Wrappers.<UserOrg>lambdaQuery().eq(UserOrg::getOrgId, orgId));
    }

    /**
     * 获取所有组织id
     * @param userId
     * @return
     */
    public List<Long> getOrgIds(Long userId) {
        List<UserOrgItemVO> orgs = proxy().getOrgs(userId);
        return orgs.stream().map(UserOrgItemVO::getOrgId).distinct().collect(Collectors.toList());
    }

    /**
     * 获取所有岗位id
     * @param userId
     * @return
     */
    public List<Long> getPostIds(Long userId) {
        List<UserOrgItemVO> orgs = proxy().getOrgs(userId);
        return orgs.stream().map(UserOrgItemVO::getPostId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
    }

    /**
     * 获取主职部门
     * @param userId
     * @return
     */
    public UserOrgItemVO getMain(Long userId) {
        List<UserOrgItemVO> orgs = proxy().getOrgs(userId);
        for (UserOrgItemVO org : orgs) {
            if (Boolean.TRUE.equals(org.getMain())) {
                return org;
            }
        }
        return null;
    }

}
